package br.ufpe.cin.tose.copapolling;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.Calendar;

import android.annotation.SuppressLint;
import android.app.AlarmManager;
import android.app.IntentService;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.IBinder;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.os.SystemClock;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.Window;
import android.view.WindowManager;
import android.view.WindowManager.LayoutParams;
import android.webkit.WebView;
import android.widget.Toast;

public class AtualizaService extends Service {

	public static AtualizaService atualizaService;
	public static final String NOTIFICATION = "br.ufpe.cin.tose.copapolling";
	public static final String URLTimes = "http://www.cin.ufpe.br/~salc/times";
	public static final String URLJogos = "http://www.cin.ufpe.br/~salc/jogos";
	int indiceJogos = 0;
	int indexSharedPreferencesTimes = 0;
	int indexSharedPreferencesJogos = 0;

	public AtualizaService() {
		atualizaService = this;

	}

	@Override
	public void onCreate() {

		cancelAlarm();
		Log.d("atualizaservice", "entrou on create service");
		Toast.makeText(this, "OnCreate Service", Toast.LENGTH_LONG).show();
		// repete();

		repete();

	}

	private PendingIntent pendingIntent;

	public void createAlarm() {
		Intent myIntent = new Intent(getApplicationContext(),
				AtualizaService.class);
		pendingIntent = PendingIntent.getService(getApplicationContext(), 0,
				myIntent, 0);
		AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
		Calendar calendar = Calendar.getInstance();
		calendar.setTimeInMillis(System.currentTimeMillis());
		calendar.add(Calendar.SECOND, 60);
		alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
				pendingIntent);
		Toast.makeText(getApplicationContext(), "Start Alarm",
				Toast.LENGTH_LONG).show();
	}

	public void cancelAlarm() {
		AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);

		alarmManager.cancel(pendingIntent);
	}

	private void repete() {

		SharedPreferences keyValues = PreferenceManager
				.getDefaultSharedPreferences(getApplicationContext());
		SharedPreferences.Editor keyValuesEditor = keyValues.edit();
		indiceJogos = keyValues.getInt("indiceJogos", 0);

		MainActivity.mainActivity.apagaSharedPreferences();
		doWork();

		/*
		 * try { Thread.sleep(60000); } catch (InterruptedException e) {
		 * Log.d("serviceatualiza", e.getMessage()); }
		 */

	}

	public void doWork() {

		GetHTML request = new GetHTML();
		request.execute(URLTimes, URLJogos + indiceJogos);

	}

	public void retornoDoWork(String times, String jogos) {

		if (times != null) {
			// ID#NomeTime#URLBandeira
			String[] timesN = times.split("@");
			for (String time : timesN) {
				saveArrayTimes(time);
			}
		}
		String[] jogosN = jogos.split("@");
		for (String jogo : jogosN) {
			saveArrayJogos(jogo);
		}
		unlockScreen();
		createNotification();

		publishResults("");
		// wl.release();

	}

	PowerManager.WakeLock wl;

	public void unlockScreen() {

		Log.i("mytag", "entrou unlock");
		/*
		 * PowerManager pm = (PowerManager)
		 * getSystemService(Context.POWER_SERVICE); wl =
		 * pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, "tag");
		 * wl.acquire();
		 */

		if (haveInternet()) {
			Log.i("mytag", "tem internet");
			notificationWithVibra();
		} else {
			Log.i("mytag", "SEM internet");
		}

		/*
		 * Window window = MainActivity.mainActivity.getWindow();
		 * window.addFlags(LayoutParams.FLAG_DISMISS_KEYGUARD);
		 * window.addFlags(LayoutParams.FLAG_SHOW_WHEN_LOCKED);
		 * window.addFlags(LayoutParams.FLAG_TURN_SCREEN_ON);
		 */

	}

	public void notificationWithVibra() {
		Notification n = new Notification(R.drawable.ic_launcher, "olaaaa",
				System.currentTimeMillis());
		PendingIntent pi = PendingIntent.getActivity(MainActivity.mainActivity,
				0, new Intent(), 0);

		n.setLatestEventInfo(MainActivity.mainActivity, "Remind Me", "olaaaa",
				pi);
		// TODO check user preferences
		n.defaults |= Notification.DEFAULT_VIBRATE;
		// n.sound = Uri.parse(RemindMe.getRingtone());
		// n.defaults |= Notification.DEFAULT_SOUND;
		n.flags |= Notification.FLAG_AUTO_CANCEL;

		NotificationManager nm = (NotificationManager) MainActivity.mainActivity
				.getSystemService(Context.NOTIFICATION_SERVICE);
		nm.notify(123456, n);
	}

	public static boolean haveInternet() {

		NetworkInfo info = (NetworkInfo) ((ConnectivityManager) MainActivity.mainActivity
				.getSystemService(Context.CONNECTIVITY_SERVICE))
				.getActiveNetworkInfo();

		if (info == null || !info.isConnected()) {
			return false;
		}
		if (info.isRoaming()) {
			// here is the roaming option you can change it if you want to
			// disable internet while roaming, just return false
			return false;
		}
		return true;
	}

	private void publishResults(String outputPath) {

		// unlockScreen();
		createAlarm();
		/*
		 * Intent intent = new Intent(NOTIFICATION); intent.putExtra("msg",
		 * outputPath); sendBroadcast(intent);
		 */
	}

	public void saveArrayTimes(String msg) {
		SharedPreferences keyValues = PreferenceManager
				.getDefaultSharedPreferences(getApplicationContext());
		SharedPreferences.Editor keyValuesEditor = keyValues.edit();
		indexSharedPreferencesTimes = keyValues.getInt("indextimes", 0);
		keyValuesEditor.putString("t" + indexSharedPreferencesTimes, msg);
		keyValuesEditor.commit();
		indexSharedPreferencesTimes++;
		keyValuesEditor.putInt("indextimes", indexSharedPreferencesTimes);
		keyValuesEditor.commit();
	}

	public void saveArrayJogos(String msg) {
		SharedPreferences keyValues = PreferenceManager
				.getDefaultSharedPreferences(getApplicationContext());
		SharedPreferences.Editor keyValuesEditor = keyValues.edit();

		indexSharedPreferencesJogos = keyValues.getInt("indexjogos", 0);

		keyValuesEditor.putString("j" + indexSharedPreferencesJogos, msg);
		keyValuesEditor.commit();

		indexSharedPreferencesJogos++;
		keyValuesEditor.putInt("indexjogos", indexSharedPreferencesJogos);
		keyValuesEditor.commit();
	}

	private void createNotification() {
		Intent intent = new Intent(this.getApplicationContext(),
				MainActivity.class);
		PendingIntent pi = PendingIntent.getActivity(getApplicationContext(),
				0, intent, 0);

		final Notification notification = new Notification.Builder(
				getApplicationContext())
				.setContentTitle(getResources().getString(R.string.app_name))
				.setContentText("Executando... Clique para abrir")
				.setSmallIcon(R.drawable.ic_launcher).setContentIntent(pi)
				.build();
		notification.flags |= Notification.FLAG_FOREGROUND_SERVICE;
		notification.flags |= Notification.FLAG_ONLY_ALERT_ONCE;

		final NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
		nm.notify(R.string.app_name, notification);
	}

	public void SetAlarm() {
		BroadcastReceiver receiver = new BroadcastReceiver() {
			@Override
			public void onReceive(Context context, Intent _) {
				Intent intent = new Intent(
						AtualizaService.atualizaService.getApplicationContext(),
						AtualizaService.class);
				startService(intent);
				// context.unregisterReceiver( this ); // this ==
				// BroadcastReceiver, not Activity
			}
		};

		this.registerReceiver(receiver, new IntentFilter(
				"br.ufpe.cin.tose.copapolling"));

		PendingIntent pintent = PendingIntent.getBroadcast(this, 0, new Intent(
				"br.ufpe.cin.tose.copapolling"), 0);
		AlarmManager manager = (AlarmManager) (this
				.getSystemService(Context.ALARM_SERVICE));

		// set alarm to fire 5 sec (1000*5) from now
		// (SystemClock.elapsedRealtime())
		manager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,
				SystemClock.elapsedRealtime() + 1000 * 5, pintent);
	}

	@Override
	public IBinder onBind(Intent arg0) {

		return null;
	}

}
